package com.xiaofu.service.impl;

import com.xiaofu.component.MailService;
import com.xiaofu.component.SmsService;
import com.xiaofu.constant.CacheKey;
import com.xiaofu.enums.BizCodeEnum;
import com.xiaofu.enums.SendCodeEnum;
import com.xiaofu.service.NotifyService;
import com.xiaofu.utils.CheckUtil;
import com.xiaofu.utils.CommonUtil;
import com.xiaofu.utils.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {

    /**
     * 验证码标题
     */
    private static String SUBJECT = "验证码";

    /**
     * 验证码内容
     */
    private static String CONTENT = "您的验证码是%s,有效期是60秒,打死也不要告诉任何人";

    /**
     *  10分钟有效
     */
    private static final int CODE_EXPIRE = 60 * 1000 * 10;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MailService mailService;

    @Autowired
    private SmsService smsService;

    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {

        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);

        String cacheValue = redisTemplate.opsForValue().get(cacheKey);

        // 如果不为空,则判断是否60秒内重复发送
        if (StringUtils.isNotBlank(cacheValue)) {
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            // 当前时间戳 - 验证码时间戳 , 如果小于60秒,则不给重复发送
            if (CommonUtil.getCurrentTimeMillis() - ttl < 1000 * 60) {
                log.error("重发发送验证码,时间间隔: {}",(CommonUtil.getCurrentTimeMillis() - ttl)/1000);
                return JsonData.buildSuccess(BizCodeEnum.CODE_LIMITED);
            }
        }

        // 拼接验证码
        String code = CommonUtil.getRandomCode(6);

        String value = code + "_" + CommonUtil.getCurrentTimeMillis();

        redisTemplate.opsForValue().set(cacheKey,value,CODE_EXPIRE, TimeUnit.MILLISECONDS);

        if (CheckUtil.isEmail(to)) {
            // 邮箱验证码
            mailService.sendMail(to,SUBJECT,String.format(CONTENT,code));
            log.info("邮箱验证码为: {}",code);
            return JsonData.buildSuccess();

        } else if (CheckUtil.isPhone(to)){
            // 短信验证码
            smsService.sendMsg(to,code);
            log.info("短信验证码为:{}",code);
            return JsonData.buildSuccess();
        }

        return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR);
    }

    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY,sendCodeEnum.name(),to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)) {
            String cacheCode = cacheValue.split("_")[0];
            if (cacheCode.equals(code)) {
                // 删除验证码
                redisTemplate.delete(cacheKey);
                return true;
            }
        }
        return false;
    }
}
